package com.librarySystem.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.librarySystem.entity.User;

@Repository
public class UserDao implements UserDaoInterface {

	@Resource
	private SessionFactory sessionFactory;

	@Resource
	private HibernateTemplate hibernateTemplate;

	@Override
	public User login(User user) {

		Session session = this.sessionFactory.getCurrentSession();
		// QBC Query by Criteria.
		Criteria criteria = session.createCriteria(User.class);

		// QBE Query by Example.
		
		criteria.add(
			Restrictions.eq("userName", user.getUserName())
		);
//		
		List<?> users = criteria.list();
		
		if (users != null && users.size() > 0) {
			return (User) users.get(0);
		}
		
		return null;
//		if (queryRestrictions.getAuthor() != null) {
//			criteria.add(Restrictions.eq("author", queryRestrictions.getAuthor()));
//		}
//		if (queryRestrictions.getName() != null) {
//			criteria.add(Restrictions.eq("name", queryRestrictions.getName()));
//		}
		
		// List<User> userResult =
		// hibernateTemplate.find("from User where userName = ? ",
		// user.getUserName());
		// if(userResult != null && userResult.size() > 0){
		//			
		// return userResult.get(0);
		// }
		// return null;
	}

	@Override
	public int register(User user) {
		List<User> findUserResult = hibernateTemplate.find(
				"from User where userName = ?", user.getUserName());
		Integer identifier = 0;
		if (findUserResult != null && findUserResult.size() > 0) {
		} else {
			Session session = sessionFactory.getCurrentSession();
			identifier = (Integer) session.save(user);
		}

		return identifier;
	}

	@Override
	public boolean updataPassWord(User user) {
		Session session = sessionFactory.getCurrentSession();
		try {
			session.merge(user);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
